import { type NextRequest, NextResponse } from "next/server"
import { v4 as uuidv4 } from "uuid"
import { getDb } from "@/lib/db-sqlite"

// 获取所有活跃的投票
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams
    const active = searchParams.get("active")

    const db = getDb()

    let polls

    if (active === "true") {
      // 获取活跃的投票
      polls = db
        .prepare(`
        SELECT p.*, 
          json_group_array(
            json_object(
              'id', o.id,
              'poll_id', o.poll_id,
              'text', o.text,
              'votes', o.votes
            )
          ) as options
        FROM polls p
        LEFT JOIN poll_options o ON p.id = o.poll_id
        WHERE p.active = 1
        GROUP BY p.id
        ORDER BY p.created_at DESC
      `)
        .all()
    } else {
      // 获取所有投票
      polls = db
        .prepare(`
        SELECT p.*, 
          json_group_array(
            json_object(
              'id', o.id,
              'poll_id', o.poll_id,
              'text', o.text,
              'votes', o.votes
            )
          ) as options
        FROM polls p
        LEFT JOIN poll_options o ON p.id = o.poll_id
        GROUP BY p.id
        ORDER BY p.created_at DESC
      `)
        .all()
    }

    // 处理 JSON 字符串
    polls = polls.map((poll) => {
      try {
        poll.options = JSON.parse(poll.options)
        // 处理空数组的情况
        if (poll.options.length === 1 && poll.options[0].id === null) {
          poll.options = []
        }
        return poll
      } catch (e) {
        poll.options = []
        return poll
      }
    })

    return NextResponse.json({ polls })
  } catch (error: any) {
    console.error("Error fetching polls:", error)
    return NextResponse.json({ error: error.message || "Failed to fetch polls" }, { status: 500 })
  }
}

// 创建新投票
export async function POST(request: NextRequest) {
  try {
    const { title, description, options } = await request.json()

    if (!title || !Array.isArray(options) || options.length < 2) {
      return NextResponse.json({ error: "Invalid poll data" }, { status: 400 })
    }

    const db = getDb()
    const pollId = uuidv4()
    const now = new Date().toISOString()

    // 开始事务
    const transaction = db.transaction(() => {
      // 插入投票
      db.prepare(`
        INSERT INTO polls (id, title, description, active, created_at)
        VALUES (?, ?, ?, ?, ?)
      `).run(pollId, title, description || null, 1, now)

      // 插入投票选项
      const insertOption = db.prepare(`
        INSERT INTO poll_options (id, poll_id, text, votes)
        VALUES (?, ?, ?, ?)
      `)

      for (const text of options) {
        insertOption.run(uuidv4(), pollId, text, 0)
      }
    })

    // 执行事务
    transaction()

    // 获取创建的投票
    const poll = db
      .prepare(`
      SELECT p.*, 
        json_group_array(
          json_object(
            'id', o.id,
            'poll_id', o.poll_id,
            'text', o.text,
            'votes', o.votes
          )
        ) as options
      FROM polls p
      LEFT JOIN poll_options o ON p.id = o.poll_id
      WHERE p.id = ?
      GROUP BY p.id
    `)
      .get(pollId)

    // 处理 JSON 字符串
    try {
      poll.options = JSON.parse(poll.options)
      // 处理空数组的情况
      if (poll.options.length === 1 && poll.options[0].id === null) {
        poll.options = []
      }
    } catch (e) {
      poll.options = []
    }

    return NextResponse.json({ poll })
  } catch (error: any) {
    console.error("Error creating poll:", error)
    return NextResponse.json({ error: error.message || "Failed to create poll" }, { status: 500 })
  }
}
